#include "head.h"

// 错误日志函数
void log_error(char *message) {
    FILE *fp = fopen(LOG_FILE, "a");
    if (fp != NULL) {
        time_t now = time(NULL);
        char time_str[64];
        strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", localtime(&now));
        fprintf(fp, "[%s] ERROR: %s\n", time_str, message);
        fclose(fp);
    }
    printf("错误: %s\n", message);
}

// 目录创建函数
int create_directory_if_not_exists(char *path) {
    #ifdef _WIN32
        char mkdir_cmd[256];
        sprintf(mkdir_cmd, "mkdir %s 2>nul", path);
        return system(mkdir_cmd);
    #else
        return mkdir(path, 0777) == 0 || errno == EEXIST;
    #endif
}

// 显示登录菜单
void show_login_menu() {
    printf("\n========== 登录菜单 ==========\n");
    printf("1. 用户登录\n");
    printf("2. 用户注册\n");
    printf("3. 修改密码\n");
    printf("4. 忘记密码\n");
    printf("0. 退出系统\n");
    printf("请选择操作: ");
}

// 显示用户菜单
void show_user_menu() {
    printf("\n========== 用户购物界面 ==========\n");
    printf("1. 浏览商品\n");
    printf("2. 今日特价\n");
    printf("3. 商品分类\n");
    printf("4. 商品搜索\n");
    printf("5. 我的购物车\n");
    printf("6. 我的订单\n");
    printf("7. 个人中心\n");
    printf("0. 退出登录\n");
    printf("请选择操作: ");
}

// 显示管理员菜单
void show_admin_menu() {
    printf("\n========== 管理员管理界面 ==========\n");
    printf("1. 商品管理\n");
    printf("2. 用户管理\n");
    printf("3. 销售统计\n");
    printf("4. 系统设置\n");
    printf("0. 退出登录\n");
    printf("请选择操作: ");
}

// 登录系统
int login_system() {
    int choice;
    scanf("%d", &choice);
    
    switch (choice) {
        case 1:
            printf("用户登录\n");
            int logged_in_id = user_login();
            if (logged_in_id >= 0) {
                // 登录成功，直接返回用户ID
                return logged_in_id;
            }
            return -1; // 登录失败返回-1
        case 2:
            printf("用户注册\n");
            User *new_user = user_register();
            if (new_user != NULL) {
                printf("注册完成，请登录\n");
            }
            return -1; // 注册完成后返回登录菜单，不直接进入系统
        case 3:
            printf("修改密码\n");
            while(1){
                printf("请输入id: ");
                int id;
                scanf("%d", &id);

                User* temp_user = find_user_by_id(id);
                if(temp_user == NULL){
                    printf("用户不存在\n");
                    continue;
                }

                printf("请输入新密码: ");
                char new_password[50];
                scanf("%s", new_password);
                int result = change_password(id, new_password);
                if(result == 0){
                    break;
                }
            }
            return -1;
        case 4:
            printf("忘记密码\n");
            printf("请输入用户名: ");
            char username[50];
            scanf("%s", username);
            printf("请输入联系方式: ");
            char contact[100];
            scanf("%s", contact);
            reset_password(username, contact);
            return -1;
        case 0:
            return -1; // 退出
        default:
            printf("无效选择，请重新输入\n");
            return -1;
    }
}

// 用户菜单
int user_menu(int user_id){
    int choice;
    
    while (1) {
        show_user_menu();
        scanf("%d", &choice);
        switch (choice) {
            case 1:
                printf("浏览商品\n");
                show_all_goods();
                break;
            case 2:
                printf("今日特价\n");
                show_special_goods();
                break;
            case 3:
                printf("商品分类\n");
                printf("请输入要查看的商品分类: ");
                char category[50];
                scanf("%s", category);
                show_goods_by_category(category);
                break;
            case 4:
                printf("商品搜索\n");
                printf("1. 按ID搜索\n2. 按名称搜索\n请选择: ");
                int search_choice;
                scanf("%d", &search_choice);
                if (search_choice == 1) {
                    char goods_id[20];
                    printf("请输入商品ID: ");
                    scanf("%s", goods_id);
                    Goods *goods = find_goods_by_id(goods_id);
                    if (goods != NULL) {
                        show_goods(goods);
                    } else {
                        printf("未找到该商品！\n");
                    }
                } else if (search_choice == 2) {
                    char goods_name[100];
                    printf("请输入商品名称: ");
                    scanf("%s", goods_name);
                    Goods *goods = find_goods_by_name(goods_name);
                    if (goods != NULL) {
                        show_goods(goods);
                    } else {
                        printf("未找到该商品！\n");
                    }
                }
                break;
            case 5:
                printf("我的购物车\n");
                // 购物车功能：这里简化处理，直接创建订单
                printf("请输入要购买的商品ID: ");
                char buy_goods_id[20];
                scanf("%s", buy_goods_id);
                printf("请输入购买数量: ");
                int quantity;
                scanf("%d", &quantity);
                create_order(user_id, buy_goods_id, quantity);
                break;
            case 6:
                printf("我的订单\n");
                show_user_orders(user_id);
                
                // 提供订单操作选项
                printf("\n请输入要操作的订单ID（或输入0返回）: ");
                char order_id[50];
                scanf("%s", order_id);
                if (strcmp(order_id, "0") != 0) {
                    Order *order = find_order_by_id(order_id);
                    if (order != NULL && order->user_id == user_id) {
                        printf("1. 支付订单\n2. 取消订单\n请选择操作: ");
                        int order_choice;
                        scanf("%d", &order_choice);
                        if (order_choice == 1) {
                            pay_order(order_id);
                        } else if (order_choice == 2) {
                            cancel_order(order_id);
                        }
                    }
                }
                break;
            case 7:
                printf("个人中心\n");
                User *user = find_user_by_id(user_id);
                if (user != NULL) {
                    show_user_info(user);
                    printf("\n1. 修改密码\n2. 余额充值\n请选择操作: ");
                    int user_choice;
                    scanf("%d", &user_choice);
                    if (user_choice == 1) {
                        char new_password[50];
                        printf("请输入新密码: ");
                        scanf("%s", new_password);
                        change_password(user_id, new_password);
                    } else if (user_choice == 2) {
                        double amount;
                        printf("请输入充值金额: ");
                        scanf("%lf", &amount);
                        recharge_balance(user_id, amount);
                    }
                }
                break;
            case 0:
                printf("退出登录\n");
                return 0;
            default:
                printf("无效选择，请重新输入\n");
        }
    }
}
// 销售统计函数
void sales_statistics() {
    printf("\n========== 销售统计 ==========\n");
    
    double total_sales = 0.0;
    int total_orders = 0;
    int completed_orders = 0;
    
    // 统计销售数据
    ListNode *current = order_list;
    while (current != NULL) {
        Order *order = (Order*)current->data;
        total_orders++;
        if (order->order_status == 1) { // 已支付订单
            total_sales += order->total_amount;
            completed_orders++;
        }
        current = current->next;
    }
    
    printf("总订单数: %d\n", total_orders);
    printf("已完成订单: %d\n", completed_orders);
    printf("总销售额: %.2f元\n", total_sales);
    
    if (total_orders > 0) {
        printf("订单完成率: %.2f%%\n", (float)completed_orders / total_orders * 100);
    }
    
    printf("==============================\n");
}

// 管理员菜单
int admin_menu(){    
    int choice;
    while (1) {
        show_admin_menu();
        scanf("%d", &choice);
        switch (choice) {
            case 1:
                printf("商品管理\n");
                printf("1. 添加商品\n2. 查看所有商品\n3. 更新库存\n4. 删除商品\n请选择操作: ");
                int goods_choice;
                scanf("%d", &goods_choice);
                switch (goods_choice) {
                    case 1:
                        add_goods();
                        break;
                    case 2:
                        show_all_goods();
                        break;
                    case 3:
                        printf("请输入商品ID: ");
                        char update_id[20];
                        scanf("%s", update_id);
                        printf("请输入新库存数量: ");
                        int new_stock;
                        scanf("%d", &new_stock);
                        update_goods_stock(update_id, new_stock);
                        break;
                    case 4:
                        printf("请输入要删除的商品ID: ");
                        char delete_id[20];
                        scanf("%s", delete_id);
                        delete_goods(delete_id);
                        break;
                }
                break;
            case 2:
                printf("用户管理\n");
                printf("1. 查看所有用户\n2. 修改用户类型\n3. 余额充值\n4. 添加优惠券\n5. 删除用户\n请选择操作: ");
                int user_choice;
                scanf("%d", &user_choice);
                switch (user_choice) {
                    case 1:
                        // 显示所有用户
                        printf("\n========== 所有用户列表 ==========\n");
                        printf("%-10s %-20s %-10s %-15s %-15s %-15s\n", 
                               "用户ID", "用户名", "用户类型", "账户余额", "用户积分", "联系方式");
                        printf("------------------------------------------------------------------------------------\n");
                        
                        ListNode *user_current = user_list;
                        while (user_current != NULL) {
                            User *user = (User*)user_current->data;
                            char *type_str;
                            switch (user->user_type) {
                                case -1: type_str = "封号用户"; break;
                                case 0: type_str = "普通会员"; break;
                                case 1: type_str = "VIP会员"; break;
                                case 2: type_str = "SVIP会员"; break;
                                case 3: type_str = "管理员"; break;
                                default: type_str = "未知类型"; break;
                            }
                            printf("%-10d %-20s %-10s %-15.2f %-15.2f %-15s\n",
                                   user->user_id,
                                   user->username,
                                   type_str,
                                   user->balance,
                                   user->points,
                                   user->contact);
                            user_current = user_current->next;
                        }
                        printf("====================================================================================\n");
                        break;
                    case 2:
                        printf("请输入用户ID: ");
                        int user_id;
                        scanf("%d", &user_id);
                        printf("请输入新用户类型（0-普通会员, 1-VIP, 2-SVIP, 3-管理员, -1-封号）: ");
                        int new_type;
                        scanf("%d", &new_type);
                        change_user_type(user_id, new_type);
                        break;
                    case 3:
                        printf("请输入用户ID: ");
                        int recharge_id;
                        scanf("%d", &recharge_id);
                        printf("请输入充值金额: ");
                        double recharge_amount;
                        scanf("%lf", &recharge_amount);
                        recharge_balance(recharge_id, recharge_amount);
                        break;
                    case 4:
                        printf("请输入用户ID: ");
                        int coupon_id;
                        scanf("%d", &coupon_id);
                        printf("请输入优惠券金额: ");
                        double coupon_amount;
                        scanf("%lf", &coupon_amount);
                        add_coupons(coupon_id, coupon_amount);
                        break;
                    case 5:
                        printf("请输入要删除的用户ID: ");
                        int delete_user_id;
                        scanf("%d", &delete_user_id);
                        delete_user(delete_user_id);
                        break;
                }
                break;
            case 3:
                printf("销售统计\n");
                sales_statistics();
                printf("\n1. 查看所有订单\n请选择操作: ");
                int stat_choice;
                scanf("%d", &stat_choice);
                if (stat_choice == 1) {
                    show_all_orders();
                }
                break;
            case 4:
                printf("系统设置\n");
                printf("1. 初始化系统数据\n2. 备份数据\n请选择操作: ");
                int sys_choice;
                scanf("%d", &sys_choice);
                if (sys_choice == 1) {
                    printf("初始化系统数据将清空所有数据，确定继续？(y/n): ");
                    char confirm;
                    scanf(" %c", &confirm);
                    if (confirm == 'y' || confirm == 'Y') {
                        // 清空链表并保存空数据到文件
                        free_list_with_data(goods_list, free);
                        goods_list = NULL;
                        save_all_goods();
                        
                        free_list_with_data(order_list, free);
                        order_list = NULL;
                        save_all_orders();
                        
                        printf("系统数据已初始化！\n");
                    }
                }
                break;
            case 0:
                printf("退出登录\n");
                return 0;
            default:
                printf("无效选择，请重新输入\n");
        }
    }
}
